package com.aivin.lib_reader.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.aivin.lib_reader.R;
import java.util.List;

import com.aivin.lib_reader.icallback.ColorSelectCallBack;

public class RecyclerViewAdapter extends RecyclerView.Adapter {
    private int mSelectedItem = -1;
    private List<Integer> mLabels;
    private ColorSelectCallBack selectCallBack;

    public RecyclerViewAdapter(List<Integer> labels, ColorSelectCallBack selectCallBack) {
        mLabels = labels;
        this.selectCallBack = selectCallBack;
    }

    @NonNull
    @Override
    public ChooseHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        View view = LayoutInflater.from(context).inflate(R.layout.item_choose, parent, false);
        return new ChooseHolder(view);
    }


    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        ChooseHolder chooseHolder = (ChooseHolder) holder;
        chooseHolder.item_img.setBackgroundColor(mLabels.get(position));
        if (position == mSelectedItem) {
            chooseHolder.item_img.setSelected(true);
        } else {
            chooseHolder.item_img.setSelected(false);
        }
    }

    @Override
    public int getItemCount() {
        return mLabels.size();
    }

    class ChooseHolder extends RecyclerView.ViewHolder {
        private ImageView item_img;

        ChooseHolder(View itemView) {
            super(itemView);
            item_img = itemView.findViewById(R.id.item_img);
            View.OnClickListener clickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mSelectedItem = getAdapterPosition();
                    selectCallBack.onSelect(mLabels.get(mSelectedItem), mSelectedItem);
                    notifyDataSetChanged();
                }
            };
            item_img.setOnClickListener(clickListener);
        }
    }
}

